#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DHTesp.h"
DHTesp dht;
const char *ssid = "0_SevDaisy Mate 10";
const char *password = "66752928";
const char *mqtt_server = "47.93.197.229";
const char *client_id = "clientID_31801146";
const char *user_name = "dashboard_zyy";
const char *user_passwd = "123456";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (500)

int beat_cnt = 0;

void setup_wifi()
{
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String str = "";
  for (int i = 0; i < length; i++)
  {
    str += (char)payload[i];
  }
  Serial.println(str);
}
void reconnect()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    if (client.connect(client_id, user_name, user_passwd))
    {
      Serial.println("connected");
      client.publish("zyy/dht11/heart_beat", "zyy so cute");
      client.subscribe("zyy/dht11/receive");
    }
    else
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void send_msg()
{
  if (readDHT11(800))
  {
    const size_t capacity = JSON_OBJECT_SIZE(6);
    DynamicJsonBuffer jsonBuffer(capacity);

    JsonObject &root = jsonBuffer.createObject();
    root["stu_order"] = 31801146;
    root["stu_name"] = "章一砚";
    root["tty_name"] = "百元ESP8266_1";
    root["temperature"] = dht.getTemperature();
    root["humidity"] = dht.getHumidity();
    root["username"] = "IOT Lab 9";

    char msg[MSG_BUFFER_SIZE] = {
        0,
    };
    root.printTo(msg);
    Serial.println(msg);
    client.publish("zyy/dht11/send", msg, MQTTQOS1);
  }
  else
  {
    Serial.println("DHT11 Error");
  }
}
bool readDHT11(int delay_parm)
{
  bool out;
  delay(dht.getMinimumSamplingPeriod());
  out = (dht.getStatusString() == "OK");
  // humidity = dht.getHumidity();
  // temperature = dht.getTemperature();
  delay(delay_parm);
  return out;
}
void setup()
{
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  dht.setup(5, DHTesp::DHT11);
}
void loop()
{
  if (!client.connected())
  {
    reconnect();
  }
  client.loop();
  unsigned long now = millis();
  if (now - lastMsg > 2000)
  {
    send_msg();
  }
}